<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="../vue.js"></script>
    <script src="../axios.min.js"></script>
    <script src="https://cdn.staticfile.org/lodash.js/4.17.21/lodash.min.js"></script>
  </head>
  <body>
    <div id="app">
      <user-input v-on:tanslate-val="receiveVal"></user-input>
      <search-suggests :list="suggests"></search-suggests>
    </div>
    <script>
      console.log(_);
      Vue.component("user-input", {
        template: '<input type="text" v-model="val" />',
        data: function () {
          return {
            val: "123",
          };
        },
        watch: {
          val: function (n) {
            // console.log(n);
            this.$emit("tanslate-val", n);
          },
        },
      });
      Vue.component("search-suggests", {
        props: ["list"],
        template: `
        <ul>
            <li v-for="item in list">{{item[0]}}</li>
        </ul>`,
      });

      new Vue({
        el: "#app",
        data: {
          suggests: [],
        },
        created: function () {
          this.debouncedGetJson = _.debounce(this.getJson, 3000);
          //   debouncedGetJson不需要加入响应式系统  this是一个vue实例对象
        },
        methods: {
          getJson: function (n) {
            axios
              .get(
                "https://api.kele8.cn/agent/https://suggest.taobao.com/sug?code=utf-8&q=" +
                  n
              )
              .then((response) => {
                console.log(response.data.result, this);
                this.suggests = response.data.result;
              });
          },
          //  var debouncedGetJson =  _.debounce(calculateLayout, 150)
          receiveVal: function (n) {
            // console.log("parent", n);

            // 获取到子组件传过来的新值
            // 根据新值获取建议

            if (n) {
              this.debouncedGetJson(n);
            } else {
              this.suggests = [];
            }
          },
        },
      });
    </script>
  </body>
</html>
